package com.seanLab.service;

/**
 * Created by ailly on 17-8-26.
 */

import com.seanLab.domain.*;
import com.seanLab.dto.EditorArticleDto;
import com.seanLab.dto.SuggestArticleKeywordsDto;
import com.seanLab.dto.SuggestModelArticleDto;
import com.seanLab.repository.ArticleRepo;
import com.seanLab.repository.ImageRepo;
import com.seanLab.tool.DataExtractor;
import com.seanLab.tool.TagSuggestor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.*;

@Service
public class ArticleService {
//    @Autowired
//    @Qualifier("fakeArticle")
//    private ArticleDao articleDao;
//    @Autowired
//    @Qualifier("fakeImage")
//    private ImageDao imageDao;

    @Autowired
    private ArticleRepo articleRepo;
    @Autowired
    private ImageRepo imageRepo;

    public Body insertArticle(EditorArticleDto editorArticleDto) {
        //articleRepo.deleteAll();
        //imageRepo.deleteAll();

        //校验数据完整性
        if (isValid(editorArticleDto) ) {
            // transfer editorArticle to article
            Article transArticle_raw = null;
            transArticle_raw = mapArticles(editorArticleDto);

            //插入未打标签的图片 (已经包括将imgID添加到Article中的操作)
            List<Image> transImageList_raw = getImageCollectionFormArticle(transArticle_raw);

            if (transImageList_raw != null) {
                //this.imageDao.insertImageCollection(transImageList_raw);
                this.imageRepo.save(transImageList_raw);
                //插入文章
                //this.articleDao.insertArticle(transArticle_raw);
                this.articleRepo.save(transArticle_raw);

                //抽取文章及图片标签
                Article transArticle_keyword = this.extractKeywordsFromArticle(transArticle_raw);
                List<Image> transImageList_tag = this.extractImgTagsFromArticle(transArticle_raw, transImageList_raw);


                //处理图片后，更新article
                //this.articleDao.updateArticleById(transArticlex_keyword);
                this.articleRepo.save(transArticle_keyword);

                //更新图片的标签
                //this.imageDao.updateImageCollection(transImageList_tag);
                this.imageRepo.save(transImageList_tag);

            } else {

            }
            return Body.getResponseBody(0);
        }
        return Body.getResponseBody(1);
    }

    private Article mapArticles (EditorArticleDto editorArticleDto){
        Article tmpArticle_mapFromEditorArticle = new Article();
        tmpArticle_mapFromEditorArticle.setArticleID("articleID-" + UUID.randomUUID().toString());
        //tmpArticle_mapFromEditorArticle.setArticleID("1000");

        // 映射能直接使用的属性
        tmpArticle_mapFromEditorArticle.setTypes(editorArticleDto.getTypes());
        tmpArticle_mapFromEditorArticle.setSource(editorArticleDto.getSource());
        tmpArticle_mapFromEditorArticle.setChannel(editorArticleDto.getChannel());
        tmpArticle_mapFromEditorArticle.setTags(editorArticleDto.getTags());
        tmpArticle_mapFromEditorArticle.setUrl(editorArticleDto.getUrl());
        tmpArticle_mapFromEditorArticle.setTitle(editorArticleDto.getTitle());
        tmpArticle_mapFromEditorArticle.setCode(editorArticleDto.getContent());

        // 处理不能直接使用的属性
        tmpArticle_mapFromEditorArticle.setCategory(DataExtractor.getCategoryFromArticle(editorArticleDto.getCategory()));
        tmpArticle_mapFromEditorArticle.setContent(DataExtractor.getContentFormArticle(editorArticleDto.getContent()));

        return tmpArticle_mapFromEditorArticle;
    }


    //此方法负责图片的下载
    private List<Image> getImageCollectionFormArticle(Article article) {
        //@田添星 使用DataExtractor从文章html中抽取图片
        //功能：抽取图片，并过滤，下载，返回最终的干净的图片列表，注意，此处图片列表为 ArrayList<Image>，
        //TagInfo留空即可
        //实现后补全代码
        //List<Image> tmpImgList = DataExtractor.getImgList(article.getCode());

        //TODO 20171005 @田添星 Article及Image已修改，需要重写DataExtractor
        List<Image> tmpImgList = DataExtractor.getImgList(article.getCode(), article.getArticleID());
        //抽取imgList中的imgID
        List<String> tmpImgID = new ArrayList<String>();
        for (Image img : tmpImgList) {
            tmpImgID.add(img.getImgID());
        }

        //更新article的imgList
        article.setImgID(tmpImgID);

        return tmpImgList;
    }

    private Article extractKeywordsFromArticle(Article article) {
        Article tmpArticle = article;
        //@吴小波 TagSuggestor应返回该文章对应的关键词. e.g., articleTagList
        //@吴小波 填充以下代码
        //TagSuggestor t1 = new TagSuggestor();
        //SuggestModelArticleDto suggestModelArticleDto = DataExtractor.extractModelArticleFromArticle(article);
        //List<String> keywords = t1.doKeyword(suggestModelArticleDto);

        //fake data
        //List<String> keywords = new ArrayList<String>(Arrays.asList("keyword1", "keyword2"));

        //FIXME 吴晓波代码实现部分（not reviewed）
        TagSuggestor ts = new TagSuggestor();
        ts.loadModel("workingDir" + File.separator + "model_22029");
        SuggestModelArticleDto suggestModelArticleDto = DataExtractor.extractModelArticleWithoutImgsFromArticle(article);
        List<SuggestArticleKeywordsDto> keywords = ts.doKeyword(suggestModelArticleDto);

        tmpArticle.setKeywords(keywords);
        return tmpArticle;
    }

    private List<Image> extractImgTagsFromArticle(Article article, List<Image> imageList) {
        List<Image> tmpImgList = new ArrayList<Image>(imageList);
        //抽取图片关键词

        //ArrayList<ArrayList<TagInfo>> articleTagList = new ArrayList<ArrayList<TagInfo>>();
        //List<TagInfo> imgTagList = new ArrayList<>();

        // @吴小波 TagSuggestor应返回该文章对应的图片的标签列表. e.g., articleTagList
        // @吴小波 填充以下代码
        //TagSuggestor t1 = new TagSuggestor();
        //SuggestModelArticleDto suggestModelArticleDto = DataExtractor.extractModelArticleFromArticle(article);
        //ArrayList<ArrayList<TagInfo>> articleTagList = t1.doTag(suggestModelArticleDto);

        //FIXME 吴晓波代码实现部分（not reviewed）
        TagSuggestor ts = new TagSuggestor();
        ts.loadModel("workingDir" + File.separator + "model_22029");
        SuggestModelArticleDto suggestModelArticleDto = DataExtractor.extractModelArticleFromArticle(article, imageList);
        List<List<TagInfo>> articleTagList = ts.doTag(suggestModelArticleDto);


        for (Image tmpImg : tmpImgList) {
            //设置图片关键词

            //添加测试伪标签
            //List<TagInfo> tagList = new ArrayList<TagInfo>( Arrays.asList(new TagInfo("tag_0001", "复旦大学",  "article", 9.0), new TagInfo("tag_0002", "985",  "article", 7.5 ), new TagInfo("tag_0003", "上海", "article", 5.0) )  );
            //tmpImg.setImgTagList(tagList);

            //TODO @吴小波 添加模型后修改此处
            //TODO 将图片的标签设置为抽取出的标签
            //TODO int index = tmpImgList.indexOf(tmpImg);
            //TODO tmpImg.setImgTagList(articleTagList.get(index));

            //FIXME 吴晓波代码实现部分（not reviewed）
            int index = tmpImgList.indexOf(tmpImg);
            tmpImg.setImgTagList(articleTagList.get(index));

        }
        return tmpImgList;
    }

    private boolean isValid(EditorArticleDto editorArticleDto) {
        return true;
    }

//    private SuggestModelArticleDto extractModelArticleFromArticle(Article article) {
//        SuggestModelArticleDto suggestModelArticleDto = new SuggestModelArticleDto();
//        //TODO 从article中抽取出modelArticle
//        return suggestModelArticleDto;
//    }


    public Collection<Article> getAllArticles() {
        return this.articleRepo.findAll();

//        List<Article> existArticleList =  new ArrayList<>();
//        existArticleList.add(this.articleRepo.findByArticleID("5cc3d27e-f8d9-43b6-abc1-ae36f4e12c44"));
//        return existArticleList;
        //return this.articleDao.getAllArticles();
    }

}
